package com.xwyzsn.rentcar.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xwyzsn.rentcar.entity.User;
import com.xwyzsn.rentcar.mapper.UserMapper;
import com.xwyzsn.rentcar.utils.JwtToken;
import com.xwyzsn.rentcar.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.*;

@Service
public class UserService  {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtToken jwtToken;
    public List<User> getOne(Map<String,?>payload){
        if (payload.isEmpty()){
            return userMapper.getAll();
        }
        Integer id = (Integer) payload.get("id");
        return userMapper.getOne(id);
    }

    public Boolean addOne(Map<String,?>payload){
        if (payload.isEmpty())return false;
        User user =  new User();//setEntity(payload,User.class);
        String username = (String) payload.get("username");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1 != null){
            return false;
        }
        String password = (String) payload.get("password");
        String tel = (String) payload.get("tel");
        String roles = (String) payload.get("roles");
        user.setUsername(username);
        user.setPassword(password);
        user.setTel(tel);
        user.setRoles(roles);
        return userMapper.addOne(user);
    }

    public Boolean deleteOne(Map<String,?>payload){
        Integer id = (Integer) payload.get("id");
        return userMapper.deleteOne(id);
    }

    public Integer updateOne(Map<String,?>payload){
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.eq("id",payload.get("id"));

        userUpdateWrapper.set("username",payload.get("username"));
        userUpdateWrapper.set("password",payload.get("password"));
        userUpdateWrapper.set("tel",payload.get("tel"));
        return userMapper.update(userUpdateWrapper);
    }
    public static <T> T setEntity(Map<String, ?> payload, Class<T> clazz) {
        try {
            T entity = clazz.newInstance();
            Field[] fields = clazz.getDeclaredFields();

            for (Field field : fields) {
                String fieldName = field.getName();
                if (payload.containsKey(fieldName)) {
                    field.setAccessible(true);
                    Object value = payload.get(fieldName);

                    // Handle type conversions if necessary
                    if (field.getType() == Integer.class && value instanceof Number) {
                        value = ((Number) value).intValue();
                    } else if (field.getType() == Float.class && value instanceof Number) {
                        value = ((Number) value).floatValue();
                    } else if (field.getType() == Date.class) {
                        value = (Date) value;
                    }else if (field.getType() == String.class && value instanceof String){
                        value = (String) value;
                    }
                    field.set(entity, value);
                }
            }
            return entity;
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace(); // Handle or log the exception as needed
            return null;
        }
    }
    private User setEntity(Map<String, ?> payload) {
        return setEntity(payload,User.class);
    }

    public Result login(Map<String, ?> payload) {
        if (payload.isEmpty())return Result.fail("参数为空");
        String username = String.valueOf(payload.get("username"));
        String password =  String.valueOf(payload.get("password"));
//        User user = userMapper.login(username,password);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        queryWrapper.eq("password",password);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null){
            return Result.fail("用户名或密码错误");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("token",user);
        map.put("name",user.getUsername());
        map.put("roles",user.getRoles());
        map.put("password",user.getPassword());
        map.put("tel",user.getTel());
        String token =  jwtToken.createToken(user.getUsername(),user.getPassword(),user.getRoles());
        map.put("token",token);
        map.put("userId",user.getId());
        return Result.succ(map);
    }

    public Result getInfo(Map<String, ?> payload) {
        if (payload.isEmpty())return Result.fail("参数为空");
        String token = String.valueOf(payload.get("token"));
        String[] tokens = jwtToken.parseToken(token);
        if(tokens == null)return Result.fail("token解析失败");

        String username = tokens[0];
        String password = tokens[1];
        List<String>roles = Arrays.asList(tokens[2].split(","));

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        queryWrapper.eq("password",password);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null){
            return Result.fail("用户名或密码错误");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("token",user);
        map.put("name",user.getUsername());
        map.put("roles",roles);
        map.put("password",user.getPassword());
        map.put("tel",user.getTel());
        map.put("userId",user.getId());
        return Result.succ(map);
    }
}
